from typing import Generic,TypeVar,Optional
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional,TypeVar,Generic
from fastapi.encoders import jsonable_encoder


T = TypeVar('T')

class StandardResponse(BaseModel,Generic[T]):
    statusCode:int
    message: str
    data:Optional[T] = None
    
    # 支持泛型，让 data 可以是任意类型
    class Config:
        arbitrary_types_allowed = True
        

def success(data= None,message:str = "success",status_code:int=200):
    return JSONResponse(
        content={
            "statusCode": 200,
            "message": message,
            "data": jsonable_encoder(data)  # ✅ 关键：自动处理 datetime、model 等
        },
        status_code=200
    )
    # response_model = StandardResponse[T](statusCode=status_code,message = message,data=data)
    # return JSONResponse(
    #     content=response_model.dict(),
    #     status_code=status_code
    # )
    

def fail(data:Optional[T] = None,message:str = "error",status_code:int=400):
    response_model = StandardResponse[T](statusCode=status_code,message = message,data=data)
    return JSONResponse(
        content=response_model.dict(),
        status_code=status_code
    )